<?php

namespace app\admin\controller\kefu;

use Throwable;
use think\facade\Db;
use app\worker\library\kefu\Common;
use app\common\controller\Backend;

/**
 * 用户管理
 */
class User extends Backend
{
    /**
     * User模型对象
     * @var object
     * @phpstan-var \app\admin\model\kefu\User
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected array $withJoinTable = ['sysUser', 'admin'];

    protected string|array $quickSearchField = ['id', 'nickname', 'sysUser.nickname', 'admin.nickname'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\kefu\User();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->visible(['sysUser' => ['nickname'], 'admin' => ['nickname']])
            ->order($order)
            ->paginate($limit)->each(function ($item) {
                $item->nickname = Common::trueValue([
                    $item->nickname,
                    $item->admin?->nickname,
                    $item->sysUser?->nickname,
                    Common::getTouristNickname($item->id),
                ]);
            });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if (empty($data['user_id'])) $data['user_id'] = '';
            if (empty($data['admin_id'])) $data['admin_id'] = '';

            if (isset($data['identity']) && $data['identity'] != 'tourist' && (empty($data['user_id']) && empty($data['admin_id']))) {
                $this->error('请设置绑定的会员或管理员！');
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);

            if (empty($data['user_id'])) $data['user_id'] = '';
            if (empty($data['admin_id'])) $data['admin_id'] = '';

            if (isset($data['identity']) && $data['identity'] != 'tourist' && (empty($data['user_id']) && empty($data['admin_id']))) {
                $this->error('请设置绑定的会员或管理员！');
            }

            // 将身份设置为客服代表时，清理不完整的会话信息
            if (isset($data['identity']) && $data['identity'] == 'csr' && $row->identity != 'csr') {
                Db::name('kefu_session')
                    ->where('user_id', $id)
                    ->where('session_user_id', 0)
                    ->delete();
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }
}